#!/usr/bin/env python
# -*- coding: utf-8 -*-

import tornado.web
import render
import time


class BaseHandler(tornado.web.RequestHandler):


    def __init__(self, *args, **kwargs):
        tornado.web.RequestHandler.__init__(self, *args, **kwargs)
        self.get = self._deco_method(self.get)
        self.post = self._deco_method(self.post)
        self.put = self._deco_method(self.put)
        self.delete = self._deco_method(self.delete)
        self.rt = None
        self._result_buffer = []
        

    def get_error_html(self, status_code, **kwargs):
        """ error html """
        desc = {
            401: 'xxxxx',
            402: 'yyyyy',
            500: 'Internal Server Error',
            405: 'method not allowed',
        }

        result = {'status': 'failed', 'code': kwargs.get('code', status_code), 'desc': kwargs.get('desc', desc.get(status_code, ''))}
        return result

    def write(self, chunk):
        if chunk is not None:
            self._result_buffer.append(chunk)

    def flush(self, include_footers=False):
        self._set_content_type()
        self._flush_result_buffer()
        tornado.web.RequestHandler.flush(self, include_footers)

    def finish(self, chunk=None):
        if chunk is not None:
            self.write(chunk)
        self._flush_result_buffer()
        tornado.web.RequestHandler.finish(self)

    def _flush_result_buffer(self):
        for r in self._result_buffer:
            tornado.web.RequestHandler.write(self, self._format_result(r))
        self._result_buffer = []

    def _format_result(self, chunk):
        _need_format = not isinstance(chunk, (bool, int, long, float, basestring))
        if _need_format:
            if self.rt == 'xml':
                chunk = render.xml(chunk)
            else:
                chunk = render.json(chunk)
                if self.rt == 'text':
                    chunk = self.render_string('templates/json_format.html', json_content=chunk)
                else:
                    _method = self.get_argument('callback', '').strip()
                    if _method:
                        chunk = '{0}({1})'.format(_method, chunk)
        return chunk

    def _set_content_type(self):
        if self.rt == 'xml':
            self.set_header('Content-Type', 'text/xml; charset=UTF-8')
        elif self.rt == 'json':
            self.set_header('Content-Type', 'application/json; charset=UTF-8')

    def _fix_rt(self, args):
        if not self.rt:
            self.rt = args[-1] or 'json'
            args = args[:-1]
        return args

    def _deco_method(self, fn):
        def _func(*args):
            args = self._fix_rt(args)
            fn(*args)
            
            # check pid
            #if self._check_pid():
            #    fn(*args)
            #else:
            #   self.send_error(403, desc='invalid pid')               

        return _func
